// //提交登录
//定义一个获取数据的方法 = > 用于分页
$.ajaxSetup({
  beforeSend: function () {
    $("#loading").fadeIn();
    // console.log('开发请求之前....');
  },
  complete: function (xhr) {
    $("#loading").fadeOut();
    $(document).ajaxError(function (err) {
      console.log(err);
    });
  },
  dataType: "json",
});

// deng登陆监视及方法
document.onkeydown = function (e) {
  var theEvent = window.event || e;
  var code = theEvent.keyCode || theEvent.which;
  if (code == 13) {
    $("#login").click();
  }
};

$("#login").click(function (params) {
  var username = $("input[name='username']").val();
  var password = $("input[name='password']").val();
  if (username == "" || password == "") {
    layer.confirm("请输入登录信息");
    return false;
  }
  var tmp = $("#loginForm").serializeArray(); //表单序列化 = > 直接将表单的数据内容提取为查询字符串格式(键=值)
  var Formdata = formatData(tmp); //格式化数据
  ajaxUtil.ajaxRequest(
    "/loginApi",
    Formdata,
    function (res) {
      Toast(res.msg, "success", 500, 1000);
      // narn("", "成功:" + err.msg, "提示");
      // alert(res)
      // console.log("loginRes:", res);
      var cname = res.cname || null;
      setCookie("cname", cname, 365);
      //  window.location.href("/");  //可以返回
      window.location.replace("/"); //不可以返回
    },
    function (err) {
      narn("error", "失败:" + err.msg, "提示");
      //处理请求失败
      console.log(err.msg);
      // alert(err.msg);
      Toast(err.msg, "error", 2000, 2000);
      return true;
    },
    {
      loadingId: "body",
    }
  );
});

function setCookie(cname, cvalue, exdays) {
  // var d = new Date();
  // d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  // var expires = "expires=" + d.toUTCString();
  // document.cookie = cname + "=" + cvalue + "; " + expires;
  var exp = new Date();
  exp.setTime(exp.getTime() + exdays * 24 * 60 * 60 * 1000); //6天过期
  document.cookie = cname + "=" + unescape(cvalue) + ";expires=" + exp.toGMTString();
  return true;
}

//读取cookie
function getCookie(name) {
  var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
  // var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
  if (arr) return unescape(arr[2]);
  return null;
}

//封装一个处理表单序列化数据格式
function formatData(array) {
  var data = {};
  //处理需要提交的数据
  $.each(array, function (index, item) {
    data[item.name] = item.value;
  });
  return data;
}
